<template>
  <div class="login">
    <!--  顶部  -->
    <div class="el-login-top">
      <!-- <img src="@/assets/images/yidong.png" /> -->
      <div class="line"></div>
      <!-- <span>广西移动|网络成本智能稽核系统</span> -->
    </div>
    <el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form">
      <h3 class="title">登 录</h3>
      <el-tabs v-if="loginMethods.length > 1" v-model="loginMethod" type="card" @tab-click="tabChange">
        <template v-for="item in loginMethods">
          <el-tab-pane v-if="item.name !== 'email'" :key="item.name" :label="item.label" :name="item.name" />
        </template>
      </el-tabs>
      <!--账号登录-->
      <template v-if="loginMethod === 'account'">
        <el-form-item prop="username">
          <el-input v-model="loginForm.username" type="text" auto-complete="off" placeholder="账号">
            <svg-icon slot="prefix" icon-class="user" class="el-input__icon input-icon" />
          </el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input v-model="loginForm.password" type="password" auto-complete="off" placeholder="密码"
            @keyup.enter.native="handleLogin">
            <svg-icon slot="prefix" icon-class="password" class="el-input__icon input-icon" />
          </el-input>
        </el-form-item>
        <el-form-item prop="code" v-if="captchaEnabled">
          <el-input v-model="loginForm.code" auto-complete="off" placeholder="验证码" style="width: 63%"
            @keyup.enter.native="handleLogin">
            <svg-icon slot="prefix" icon-class="validCode" class="el-input__icon input-icon" />
          </el-input>
          <div class="login-code">
            <img :src="codeUrl" @click="getCode" class="login-code-img" />
          </div>
        </el-form-item>
        <el-checkbox v-model="loginForm.rememberMe" style="margin: 0px 0px 25px 0px">记住密码</el-checkbox>
        <el-form-item style="width: 100%">
          <el-button :loading="loading" size="medium" type="primary" style="width: 100%"
            @click.native.prevent="handleLogin">
            <span v-if="!loading">登 录</span>
            <span v-else>登 录 中...</span>
          </el-button>
          <div style="float: right" v-if="register">
            <router-link class="link-type" :to="'/register'">立即注册</router-link>
          </div>
        </el-form-item>
      </template>
      <!--手机号登录-->
      <template v-if="loginMethod === 'phone'">
        <el-form-item prop="phone">
          <el-input v-model="loginForm.phone" suffix-icon="el-icon-phone-outline" placeholder="请输入手机号" :autofocus="true"
            clearable />
        </el-form-item>
        <el-form-item prop="dxcode" v-if="captchaEnabled">
          <el-input v-model="loginForm.dxcode" auto-complete="off" placeholder="短信验证码" style="width: 63%" maxlength="6"
            @keyup.enter.native="handleLogin(2)">
            <svg-icon slot="prefix" icon-class="validCode" class="el-input__icon input-icon" />
          </el-input>
          <div class="login-code">
            <!-- <router-link class="link-type" :to="'/register'">发送验证码</router-link> -->
            <div class="link-type" @click="sendCode">发送验证码</div>
          </div>
        </el-form-item>

        <button type="button" class="el-button el-button--primary el-button--medium" style="width: 100%"
          @click="handleLogin(2)">
          <span v-if="!loading">登 录</span>
          <span v-else>登 录 中...</span>
        </button>
      </template>
    </el-form>
    <!--  底部  -->
    <div class="el-login-footer">
    </div>
  </div>
</template>

<script>
import { getCodeImg, sendSmsCode } from "@/api/login";
import Cookies from "js-cookie";
import { encrypt, decrypt } from "@/utils/jsencrypt";
import {  removeToken } from '@/utils/auth'

export default {
  name: "Login",
  data() {
    return {
      loginInfo: {
        phone: null,
        phoneNumber: null,
        smsCode: null,
        fromType: null,
      },
      codeUrl: "",
      loginForm: {
        phone: "",
        username: "",
        password: "",
        rememberMe: false,
        code: "",
        dxcode: "",
        uuid: "",
      },
      loginRules: {
        username: [
          {
            required: true,
            trigger: "blur",
            message: "请输入您的账号",
          },
        ],
        password: [
          {
            required: true,
            trigger: "blur",
            message: "请输入您的密码",
          },
        ],
        code: [
          {
            required: true,
            trigger: "change",
            message: "请输入验证码",
          },
        ],
      },
      loginMethods: [
        {
          name: "account",
          label: "账号登录",
        }
        // {
        //   name: "phone",
        //   label: "手机号登录",
        // },
        // {
        //   name: "email",
        //   label: "邮箱登录",
        // },
      ],
      loginMethod: "account",
      // loginMethod: 'phone',
      loading: false,
      // 验证码开关
      captchaEnabled: true,
      // 注册开关
      register: false,
      redirect: undefined,
    };
  },
  watch: {
    $route: {
      handler: function (route) {
        this.redirect = route.query && route.query.redirect;
      },
      immediate: true,
    },
  },
  created() {
    // token登录
    this.loginToken()
    this.getCookie();
    this.getCode();
  },
  mounted() {
    this.loading = false;
  },
  methods: {
    loginToken(){
      var hash = window.location.hash;
      let token = window.location.href.split('token=')[1]
      let opsToken = window.location.href.split('opsToken=')[1]
      // 无感登录
      if(hash && token){
        hash = hash.slice(1)
        let parts = hash.split('?')
        let pathValue = parts[0]
        let opsTokenValue = parts[1].split('=')[1]
        if(pathValue && opsTokenValue){
          this.$store.dispatch("loginOpsToken", opsTokenValue).then(() => {
            this.$store.dispatch('app/toggleSideBarHide', true)
            Cookies.set('navStatus','hide')
            this.$router.push({ path: pathValue })
            // this.$router.push({ path: '/exception/bill' })
          }).catch(() => {})
        }
      }else if(opsToken){ //ifarme登录
        this.$store.dispatch("loginOpsToken", opsToken).then(() => {
          Cookies.set('navStatus','show')
          this.$router.push({ path: '/' })
        }).catch(() => {})
      }else if(token){//token登录
        // var token1 = token.replace(/%20/g,"%2B")
        this.$store.dispatch("loginToken", token).then(() => {
          Cookies.set('navStatus','show')
          // http://36.155.105.97:8861/login?token=eyJhbGciOiJIUzUxMiJ9.eyJsb2dpbl91c2VyX2tleSI6ImVmOTE4OWRhLWY0ZWItNGIzNy1iMTU1LTA1ZDkwYTc5ZWExZSJ9.PcAw3z1OmKridubCEzUFuGr7I5czPzV-w0IsxAF31gplR8lAcvzJOh3u7IYsV_3ZaufIJ_BtPeEnc1y37SsJxQ
          // http://192.168.31.177:80/login?token=zyfr/fwKWSFyB+jTTbBmRRLbPbDyj8awkI0Mbgkj4JA=
          // http://192.168.31.177:80/sso/login?token=eyJhbGciOiJIUzUxMiJ9.eyJsb2dpbl91c2VyX2tleSI6IjFlOTRiYThjLTk5Y2QtNDhlNi1hYzI4LTE0NGJhYzdlNjMzYyJ9.N_32EKJuqISo8glXxOKwXcwuh6JSxREBGgn1HMxc2R7gCK_TBfoTVoVFlb63vblArErHp9DKTCDBT5Em5JAcsg
          this.$router.push({ path: '/' })
        }).catch(() => {});
      }
    },
    sendCode() {
      //this.loginForm.dxcode = null
      // 手机号校验 如果格式正确则发送验证码
      if (/^1[3456789]\d{9}$/.test(this.loginForm.phone) == false) {
        this.$modal.msgWarning("请输入正确的手机号");
        return false;
      } else {
        this.loginInfo.phone = this.loginForm.phone;
        this.loginInfo.fromType = 1;
        sendSmsCode(this.loginInfo).then((res) => {
          if (res.code == 200) {
            this.$modal.msgSuccess(res.msg);
          } else {
            this.$modal.msgSuccess(res.msg);
            this.loginForm.dxcode = "";
          }
        });
      }

    },
    getCode() {
      getCodeImg().then((res) => {
        this.captchaEnabled =
          res.captchaEnabled === undefined ? true : res.captchaEnabled;
        if (this.captchaEnabled) {
          this.codeUrl = res.img;
          this.loginForm.uuid = res.uuid;
        }
      });
    },
    getCookie() {
      const username = Cookies.get("username");
      const password = Cookies.get("password");
      const rememberMe = Cookies.get("rememberMe");
      this.loginForm = {
        username: username === undefined ? this.loginForm.username : username,
        password:
          password === undefined ? this.loginForm.password : decrypt(password),
        rememberMe: rememberMe === undefined ? false : Boolean(rememberMe),
      };
    },
    handleLogin(loginType) {
      if (loginType != 2) {
        //账号登录
        this.$refs.loginForm.validate((valid) => {
          if (valid) {
            this.loading = true;
            if (this.loginForm.rememberMe) {
              Cookies.set("password", encrypt(this.loginForm.password), {
                expires: 30,
              });
              Cookies.set("rememberMe", this.loginForm.rememberMe, {
                expires: 30,
              });
            } else {
              Cookies.remove("username");
              Cookies.remove("password");
              Cookies.remove("rememberMe");
            }
            Cookies.set("username", this.loginForm.username, {
              expires: 30,
            });
            this.$store
              .dispatch("Login", this.loginForm)
              .then(() => {
                this.$router.push({ path:'/' })
              })
              .catch(() => {
                this.loading = false;
                if (this.captchaEnabled) {
                  this.getCode();
                }
              });
          }
        });
      } else {
        //手机号登录
        this.loginInfo.phoneNumber = this.loginInfo.phone;
        this.loginInfo.smsCode = this.loginForm.dxcode;
        this.$store
          .dispatch("Login2", this.loginInfo)
          .then(() => {
            Cookies.set('navStatus','show')
            this.$router
              .push({ path:'/' })
              .catch(() => { });
          })
          .catch(() => {
            this.loading = false;
            // if (this.captchaEnabled) {
            //     this.getCode()
            // }
          });
      }
    },
    tabChange(tab) {
      this.$refs.loginForm.clearValidate();
      this.loginForm.captcha = "";
    },
  },
};
</script>

<style rel="stylesheet/scss" lang="scss">
.login {
  height: 100%;
  background-size: cover;
  background-image: url("../assets/images/login-background.png");
}

.title {
  font-size: 18px;
  margin: 0px auto 30px auto;
  text-align: center;
  color: #080808;
}

.login-form {
  border-radius: 6px;
  background: #ffffff;
  width: 400px;
  padding: 25px 25px 5px 25px;
  position: absolute;
  top: 28%;
  left: 65%;

  .el-input {
    height: 38px;

    input {
      height: 38px;
    }
  }

  .input-icon {
    height: 39px;
    width: 14px;
    margin-left: 2px;
  }
}

.login-tip {
  font-size: 13px;
  text-align: center;
  color: #bfbfbf;
}

.login-code {
  width: 33%;
  height: 38px;
  float: right;
  text-align: right;

  img {
    cursor: pointer;
    vertical-align: middle;
  }
}

.el-login-top {
  height: 63px;
  background-color: transparent;
  line-height: 40px;
  position: fixed;
  top: 0;
  width: 100%;
  color: #fff;
  font-family: Arial;
  font-size: 12px;
  letter-spacing: 1px;

  .line {
    z-index: 2;
    width: 1px;
    position: relative;
    left: 15px;
    top: 8px;
    display: inline-block;
    height: 30px;
    border: 1px solid #e0e7f1;
  }

  img {
    margin-left: 10px;
    margin-bottom: 10px;
    max-height: 32px;
    vertical-align: middle;
  }

  span {
    position: relative;
    z-index: 2;
    padding: 0 16px;
    color: #333333;
    font-size: 18px;
    line-height: 64px;
    font-weight: 700;
    margin-left: 10px;
  }
}

.el-login-footer {
  height: 50px;
  line-height: 40px;
  background-color: #00336b;
  position: fixed;
  bottom: 0;
  width: 100%;
  text-align: center;
  color: #fff;
  font-family: Arial;
  font-size: 12px;
  letter-spacing: 1px;
}

.login-code-img {
  height: 38px;
}
</style>
